const express = require('express');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const xmlparser = require('express-xml-bodyparser');

const app = express();
const os = require('os');
const Logger = require('./utils/logger').Logger('access');
const BaseResp = require('./utils/baseResp');
const errorCode = require('./utils/errorCode');
const verifyUser = require('./utils/jwtHanlder');
const tools = require('./utils/tools');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ limit: '1mb', extended: true }));
app.use(cookieParser());
app.use(xmlparser());

/**
 * 拦截请求，生成访问日志
 */
app.use((req, res, next) => {
  req.headers.hostname = os.hostname();
  req.ip = tools.getRemoteIp(req);
  Logger.info(`${req.ip}  ${
    req.method}  ${
    req.url}  ${
    req.headers.hostname}  ${
    JSON.stringify(req.params)}  ${
    JSON.stringify(req.query)}  ${
    JSON.stringify(req.body)}`);

  next();
});

/**
 * 统一处理一些固定的参数，和固定返回值到response上面
 */
app.use((req, res, next) => {
  //  成功信息
  res.success = data => res.json(BaseResp.success(data));
  //  错误信息
  res.error = code => res.json(BaseResp.error(code));
  next();
});

app.use('/osstoken', require('./routes/oss'));
// 微信相关接口
app.use('/wxpay', require('./routes/wxpay'));

// 微信小程序相关路由
app.use('/v1', require('./routes'));

/**
 * 错误处理
 */
app.use((error, req, res, next) => {
  if (error instanceof BaseResp) {
    return res.json(error);
  }
  Logger.error(error);
  //  没有监控到到错误，统一为系统错误
  return res.json(BaseResp.error(500));
});

/**
 * catch 404 and forward to error handler
 */
app.use((req, res, next) => {
  Logger.error(req.originalUrl, '404');
  // const err = new Error('Not Found');
  // err.status = 404;
  res.error(errorCode.notFound);
});

module.exports.app = app;
